<?php
include "functions.php";

function query($params, $limit) {
	$where = "WHERE 1 = 2";
	foreach (split(",", $params) as $range) {
		list($start, $end) = split("-", $range);
		$where .= " OR (id >= " . $start . " AND id <= " . $end . ")";
	}
	$query = "SELECT * FROM mxdb.gps_trackpoint " . $where;
	$result = run_query($query);
	header("Content-type: text/xml");
	echo '<Result success="true" >';
	$north = 0;
	$east = 0;
	$south = 0;
	$west = 0;
	$mod = floor(mysql_num_rows($result) / $limit);
	$i = 0;
	while ($row = mysql_fetch_row($result)) {
		if ($i % $mod == 0) {
			$id = $row[0];
			$lap = $row[1];
			$tstamp = $row[2];
			$lat = $row[3];
			$lon = $row[4];
			$alt = $row[5];
			if ($north == 0 || $north < $lat)
				$north = $lat;
			if ($east == 0 || $east > $lon)
				$east = $lon;
			if ($south == 0 || $south > $lat)
				$south = $lat;
			if ($west == 0 || $west < $lon)
				$west = $lon;
			$id = $row[0];
			echo '<Point id="'.$row[0].'" lap="'.$row[1].'" tstamp="'.$row[2].'" lat="'.$row[3].'" lon="'.$row[4].'" alt="'.$row[5].'" dist="'.$row[6].'" />';
		}
		$i++;
	}
	echo "<Bounds north=\"" . $north . "\" east=\"" . $east . "\" south=\"" . $south . "\" west=\"" . $west . "\" />";
	$clat = (($north - $south) / 2) + $south;
	$clon = (($west - $east) / 2) + $east;
	echo "<Center lat=\"" . $clat . "\" lon=\"" . $clon . "\" />";
	echo "</Result>";
}

function tracks() {
	// Upload the tagger enteries
	// Get the min and max for each lap
	$query = "SELECT lap_id, MIN(id) as minid, MAX(id) as maxid FROM mxdb.gps_trackpoint GROUP BY lap_id";
	$result = run_query($query);
	header("Content-type: text/xml");
	echo '<Result success="true">';
	while ($row = mysql_fetch_row($result)) {
		$lap_id = $row[0];
		$min_id = $row[1];
		$max_id = $row[2];
		echo "<Track id=\"" . $lap_id . "\" start=\"" . $min_id . "\" end=\"" . $max_id . "\" />";
	}
	echo "</Result>";
}

if ($_REQUEST['q'])
	query($_REQUEST['q'], $_REQUEST['l']);
else 
	tracks();

?>
